package com.teamblueplus.viewcomic;

import java.io.File;

import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ViewFlipper;

import com.teamblueplus.ComicComicActivity;
import com.teamblueplus.R;
import com.teamblueplus.comicmaker.ComicMaker;
import com.teamblueplus.comicmaker.ImageEditorSurfaceView;

/**
 *This class is responsible for displaying the
 *finish comic page. It uses the view flipper library
 *for displaying the transition between each page
 *
 *
 * @author hanzen
 */
public class ViewComicFlipperStyle extends Activity {
	/** Called when the activity is first created. */

	private ArrayList<String> listOfImagesPath;
	private Bitmap bitmap;
	private ImageView image;
	private File[] listOfFiles;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_comic);

		listOfImagesPath = new ArrayList<String>();

		final ViewFlipper page = (ViewFlipper) findViewById(R.id.flipper);
		Button btnNext = (Button) findViewById(R.id.next);
		Button btnPrevious = (Button) findViewById(R.id.previous);
		Button btnShare = (Button) findViewById(R.id.shareBtn);

		final Animation animFlipInForeward = AnimationUtils.loadAnimation(this,
				R.anim.flipin);
		final Animation animFlipOutForeward = AnimationUtils.loadAnimation(
				this, R.anim.flipout);
		final Animation animFlipInBackward = AnimationUtils.loadAnimation(this,
				R.anim.flipin_reverse);
		final Animation animFlipOutBackward = AnimationUtils.loadAnimation(
				this, R.anim.flipout_reverse);

		this.populateImages(page);

		btnNext.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				page.setInAnimation(animFlipInForeward);
				page.setOutAnimation(animFlipOutForeward);
				page.showNext();

			}
		});

		btnPrevious.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				page.setInAnimation(animFlipInBackward);
				page.setOutAnimation(animFlipOutBackward);
				page.showPrevious();

			}
		});

//		btnEdit.setOnClickListener(new Button.OnClickListener() {
//
//			@Override
//			public void onClick(View arg0) {
//				Intent myIntent = new Intent(ViewComicFlipperStyle.this,
//						ComicMaker.class);
//				int pos = page.getDisplayedChild();
//
//				myIntent.putExtra("path", listOfFiles[pos].getAbsolutePath());
//				Log.d("h2", "path::" + listOfFiles[pos].getAbsolutePath());
//				ViewComicFlipperStyle.this.startActivityForResult(myIntent, 1);
//			}
//		});
		
		btnShare.setOnClickListener(new Button.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				int pos = page.getDisplayedChild();
				
				Intent sendIntent = new Intent();
				sendIntent.setAction(Intent.ACTION_SEND);
				sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Created by Comic Maker Android app");
				sendIntent.putExtra(Intent.EXTRA_TEXT, "Created by Comic Maker Android app");
				sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + listOfFiles[pos].getAbsolutePath()));
				sendIntent.setType("image/jpeg");
				startActivity(sendIntent);
			}
		});
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// kill activity
		if (requestCode == 1) {
			Log.d("h2", "kill view comic");
			this.finish();
		}
	}

	public void showDialogBox() {
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

		// set title
		alertDialogBuilder.setTitle("No Comic made yet");

		// set dialog message
		alertDialogBuilder
				.setMessage("Make a comic first...")
				.setCancelable(false)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								// if this button is clicked, close
								// current activity
								ViewComicFlipperStyle.this.finish();
							}
						});
		alertDialogBuilder.show();

	}

	public void populateImages(ViewFlipper page) {
		File sdCard = Environment.getExternalStorageDirectory();
		File dir = new File(sdCard.getAbsolutePath() + "/ComicMaker/");

		Log.d("h2", "outputPath::" + dir.toString());
		String filePath;
		listOfFiles = dir.listFiles();

		// if no comic made yet
		if (listOfFiles == null) {
			Log.d("h2", "NULLnullll");
			// show an alert message
			this.showDialogBox();
		} else {
			for (int i = 0; i < listOfFiles.length; i++) {
				if (listOfFiles[i].isFile()) {
					filePath = listOfFiles[i].getAbsolutePath();
					bitmap = BitmapFactory.decodeFile(filePath);

					// this.bitmap =
					// ViewComicFlipperStyle.decodeSampledBitmapFromFile(filePath,
					// 1, 90);
					this.image = new ImageView(this.getApplicationContext());
					image.setImageBitmap(this.bitmap);
					page.addView(image);

				}
			}
		}
	}

	// excerpt from google developer
	// http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
	public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth,
			int reqHeight) {

		// First decode with inJustDecodeBounds=true to check dimensions
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(path, options);

		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, reqWidth,
				reqHeight);

		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;

		Bitmap temp = BitmapFactory.decodeFile(path, options);

		return temp;
	}

	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		// Raw height and width of image
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {
			if (width > height) {
				inSampleSize = Math.round((float) height / (float) reqHeight);
			} else {
				inSampleSize = Math.round((float) width / (float) reqWidth);
			}
		}
		return inSampleSize;
	}
}